package controllers

import (
	"Myshop/models"
	"github.com/astaxie/beego"
	beelog "github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/gomodule/redigo/redis"
	"math"
	"strconv"
)

type GoodsCon struct {
	beego.Controller
}

//func GetUser(this *beego.Controller)string{
//	userName := this.GetSession("userName")
//	if userName == nil {
//		this.Data["userName"] = ""
//	}else{
//		this.Data["userName"] = userName.(string)
//		return userName.(string)
//	}
//	return ""
//}
func ShowLayout(this *beego.Controller) {
	//查询类型
	o := orm.NewOrm()
	var types []models.GoodsType
	o.QueryTable("GoodsType").All(&types)
	this.Data["types"] = types
	//获取用户信息
	GetUserName(this)

	//指定Layout
	this.Layout = "goodsLayout.html"
}
func PageTool(pageCount int, pageIndex int) []int {
	//
	var page []int
	if pageCount <= 5 {
		page = make([]int, pageCount)
		for i, _ := range page {
			page[i] = i + 1
		}
	} else if pageIndex <= 3 {
		page = []int{1, 2, 3, 4, 5}
	} else if pageIndex > pageCount-3 {
		page = []int{pageCount - 4, pageCount - 3, pageCount - 2, pageCount - 1, pageCount}
	} else {
		page = []int{pageIndex - 2, pageIndex - 1, pageIndex, pageIndex + 1, pageIndex + 2}
	}
	return page
}

func (this *GoodsCon) ShowHome() {
	username := this.GetSession("userName")
	if username == nil {
		this.Data["username"] = ""
	} else {
		this.Data["username"] = username.(string)
	}
	//获取类型数据
	var goodsTypes []models.GoodsType
	o := orm.NewOrm()
	o.QueryTable("GoodsType").All(&goodsTypes)
	this.Data["goodsTypes"] = goodsTypes
	beelog.Info("goodsTypes.Image:", goodsTypes[1].Image)
	//获取轮播图数据
	var indexGoodsBanner []models.IndexGoodsBanner
	o.QueryTable("IndexGoodsBanner").OrderBy("Index").All(&indexGoodsBanner)
	this.Data["indexGoodsBanner"] = indexGoodsBanner

	//获取促销商品数据
	var promotionGoods []models.IndexPromotionBanner
	o.QueryTable("IndexPromotionBanner").OrderBy("Index").All(&promotionGoods)
	this.Data["promotionGoods"] = promotionGoods

	//首页商品数据
	goods := make([]map[string]interface{}, len(goodsTypes))

	//向切片interface中插入类型数据
	for index, value := range goodsTypes {
		//获取对应类型的首页展示商品
		temp := make(map[string]interface{})
		temp["type"] = value
		goods[index] = temp
	}
	//商品数据
	for _, value := range goods {
		var textGoods []models.IndexTypeGoodsBanner
		var imgGoods []models.IndexTypeGoodsBanner
		//获取文字商品数据
		o.QueryTable("IndexTypeGoodsBanner").RelatedSel("GoodsType", "GoodsSKU").OrderBy("Index").Filter("GoodsType",
			value["type"]).Filter("DisplayType", 0).All(&textGoods)
		//获取图片商品数据
		o.QueryTable("IndexTypeGoodsBanner").RelatedSel("GoodsType", "GoodsSKU").OrderBy("Index").Filter("GoodsType",
			value["type"]).Filter("DisplayType", 1).All(&imgGoods)
		value["textGoods"] = textGoods
		value["imgGoods"] = imgGoods
	}
	this.Data["goods"] = goods
	//this.Layout = "goodsLayout.html"
	cart := GetCartCount(&this.Controller)
	this.Data["cartCount"] = cart
	this.TplName = "index.html"
}

//商品展示
func (this *GoodsCon) ShowGoodsDetail() {
	//接收数据
	id, err := this.GetInt("id")
	//校验数据
	if err != nil {
		beego.Error("浏览器请求错误!")
	}
	//处理数据
	o := orm.NewOrm()
	var goodsSku models.GoodsSKU
	goodsSku.Id = id
	o.Read(&goodsSku)
	o.QueryTable("GoodsSKU").RelatedSel("GoodsType", "Goods").Filter("Id", id).One(&goodsSku)
	var goodsNew []models.GoodsSKU
	//获取同类型商品根据时间的前两条商品数据
	o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType", goodsSku.GoodsType).OrderBy("Time").Limit(2,
		0).All(&goodsNew)

	//添加历史浏览记录
	//判断用户是否登录
	userName := GetUserName(&this.Controller)
	if userName != "" {
		//	查询用户信息
		o := orm.NewOrm()
		var user models.User
		user.Name = userName
		o.Read(&user, "Name")
		//	添加历史记录，用redis存储
		conn, err := redis.Dial("tcp", ":6379")
		if err != nil {
			beego.Error("redis链接错误！")
		}
		//	把以前相同商品的历史浏览记录删除
		conn.Do("lrem", "history_"+strconv.Itoa(user.Id), 0, id)
		//添加新的商品浏览记录
		conn.Do("lpush", "history_"+strconv.Itoa(user.Id), id)
		defer conn.Close()
	}
	//	渲染数据
	this.Data["goodsNew"] = goodsNew
	this.Data["goodsSku"] = goodsSku
	ShowLayout(&this.Controller)
	cart := GetCartCount(&this.Controller)
	this.Data["cartCount"] = cart
	this.TplName = "detail.html"
}

func (this *GoodsCon) ShowList() {
	//接收数据
	id, err := this.GetInt("typeId")
	if err != nil {
		beego.Error("typeID接收失败！")
	}
	pageIndex, err := this.GetInt("pageIndex")
	if err != nil {
		pageIndex = 1
	}
	//	校验数据

	//	处理数据
	ShowLayout(&this.Controller)
	o := orm.NewOrm()
	//新品
	var goodsNew []models.GoodsSKU
	o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id", id).OrderBy("Time").Limit(2,
		0).All(&goodsNew)

	//o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id",id).All(&goodsSku)

	//分页代码
	Count, err := o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id", id).Count()
	if err != nil {
		beego.Error("链接失败！")
	}

	if err != nil {
		beego.Error("错误页码！")
	}
	//一页是多少个商品
	pageSize := 4
	//总共的商品除每页放多少商品 = 多少页
	pageCount := int(math.Ceil(float64(Count) / float64(pageSize)))
	if pageIndex < 1 || pageIndex > pageCount {
		pageIndex = 1
	}
	//显示的页，数组
	pageN := PageTool(pageCount, pageIndex)

	//商品
	var goodsSku []models.GoodsSKU
	start := (pageIndex - 1) * pageSize

	prePage := pageIndex - 1

	if prePage <= 1 {
		prePage = 1
	}
	nextPage := pageIndex + 1
	if nextPage >= pageCount {
		nextPage = pageCount
	}
	//排序
	sort := this.GetString("sort")
	if sort == "" {
		o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id",
			id).OrderBy("Time").Limit(pageSize,
			start).All(&goodsSku)
		this.Data["sort"] = ""
		this.Data["goods"] = goodsSku
	} else if sort == "price" {
		o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id",
			id).OrderBy("Time").Limit(pageSize,
			start).OrderBy("Price").All(&goodsSku)
		this.Data["sort"] = "price"
		this.Data["goods"] = goodsSku
	} else {
		o.QueryTable("GoodsSKU").RelatedSel("GoodsType").Filter("GoodsType__Id",
			id).OrderBy("Time").Limit(pageSize,
			start).OrderBy("Sales").All(&goodsSku)
		this.Data["sort"] = "sales"
		this.Data["goods"] = goodsSku
	}

	this.Data["prePage"] = prePage
	this.Data["nextPage"] = nextPage
	this.Data["typeId"] = id
	this.Data["pages"] = pageN
	this.Data["goodsNew"] = goodsNew
	count := GetCartCount(&this.Controller)
	this.Data["cartCount"] = count
	this.TplName = "list.html"
	//	渲染数据
}

func (this *GoodsCon) HandelSearch() {
	//获取数据
	gName := this.GetString("goodsName")
	var goods []models.GoodsSKU
	o := orm.NewOrm()
	//	校验数据
	if gName == "" {
		o.QueryTable("GoodsSKU").All(&goods)
		this.Data["goods"] = goods
		ShowLayout(&this.Controller)
		this.TplName = "search.html"
	}

	//	处理数据

	o.QueryTable("GoodsSKU").Filter("Name__contains", gName).All(&goods)

	//	返回视图
	this.Data["goods"] = goods

	ShowLayout(&this.Controller)
	this.TplName = "search.html"
}
